<template>
  <view class="dashboard">
    <view class="stat-cards">
      <view class="stat-card">
        <view class="icon-box user-icon">
          <text class="iconfont icon-user"></text>
        </view>
        <view class="stat-info">
          <text class="label">总用户数</text>
          <text class="value">{{ stats.users?.total || 0 }}</text>
          <text class="trend">活跃用户 <text class="up">{{ stats.users?.activeUsers || 0 }}</text></text>
        </view>
      </view>
      <view class="stat-card">
        <view class="icon-box user-icon">
          <text class="iconfont icon-user-add"></text>
        </view>
        <view class="stat-info">
          <text class="label">新增用户</text>
          <text class="value">{{ stats.users?.newUsers || 0 }}</text>
          <text class="trend">最近30天</text>
        </view>
      </view>
      <view class="stat-card">
        <view class="icon-box comment-icon">
          <text class="iconfont icon-comment"></text>
        </view>
        <view class="stat-info">
          <text class="label">总评论数</text>
          <text class="value">{{ stats.comments?.total || 0 }}</text>
          <text class="trend">回复数 <text class="up">{{ stats.comments?.totalReplies || 0 }}</text></text>
        </view>
      </view>
      <view class="stat-card">
        <view class="icon-box interaction-icon">
          <text class="iconfont icon-like"></text>
        </view>
        <view class="stat-info">
          <text class="label">互动数据</text>
          <text class="value">{{ (stats.comments?.totalLikes || 0) + (stats.comments?.totalShares || 0) }}</text>
          <text class="trend">
            <text class="up">点赞 {{ stats.comments?.totalLikes || 0 }}</text> · 
            <text class="up">分享 {{ stats.comments?.totalShares || 0 }}</text>
          </text>
        </view>
      </view>
    </view>
    
    <view class="chart-section">
      <view class="section-header">
        <text class="section-title">数据趋势</text>
        <view class="section-actions">
          <text 
            v-for="(period, index) in periods" 
            :key="index" 
            class="period-btn" 
            :class="{ active: activePeriod === period.value }"
            @click="activePeriod = period.value"
          >{{ period.label }}</text>
        </view>
      </view>
      
      <view class="charts-container">
        <view class="chart-card user-chart">
          <view class="chart-header">
            <text class="chart-title">用户增长趋势</text>
          </view>
          <view class="chart-body">
            <qiun-data-charts
              type="line"
              :opts="userChartOpts"
              :chartData="userChartData"
            />
          </view>
        </view>
        
        <view class="chart-card product-chart">
          <view class="chart-header">
            <text class="chart-title">热门商品分布</text>
          </view>
          <view class="chart-body">
            <qiun-data-charts
              type="pie"
              :opts="productChartOpts"
              :chartData="productChartData"
            />
          </view>
        </view>
      </view>
    </view>
    
    <view class="recent-activities">
      <view class="section-header">
        <text class="section-title">最近活动</text>
        <text class="view-all">查看全部</text>
      </view>
      
      <view class="activities-list">
        <view class="activity-item" v-for="(activity, index) in recentActivities" :key="index">
          <view class="activity-icon" :class="activity.type">
            <text class="iconfont" :class="activity.icon"></text>
          </view>
          <view class="activity-content">
            <view class="activity-title">{{ activity.title }}</view>
            <view class="activity-desc">{{ activity.description }}</view>
          </view>
          <view class="activity-time">{{ activity.time }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'

const stats = ref({
  users: {
    total: 0,
    activeUsers: 0,
    newUsers: 0
  },
  comments: {
    total: 0,
    totalLikes: 0,
    totalShares: 0,
    totalReplies: 0
  }
})

const periods = [
  { label: '7天', value: '7d' },
  { label: '30天', value: '30d' },
  { label: '90天', value: '90d' },
  { label: '全年', value: 'year' }
]

const activePeriod = ref('30d')

const userChartOpts = {
  padding: [15, 15, 0, 15],
  enableScroll: false,
  legend: {
    show: true
  },
  xAxis: {
    boundaryGap: 'justify',
    axisLine: true,
    axisLabel: {
      rotate: 0
    }
  },
  yAxis: {
    data: [
      {
        min: 0
      }
    ]
  },
  extra: {
    line: {
      type: 'curve',
      width: 3,
      activeType: 'hollow'
    }
  },
  dataLabel: false,
  dataPointShape: true,
  dataPointShapeType: 'solid'
}

const productChartOpts = {
  padding: [15, 15, 0, 15],
  enableScroll: false,
  legend: {
    show: true,
    position: 'right'
  },
  extra: {
    pie: {
      activeOpacity: 0.5,
      activeRadius: 10,
      offsetAngle: 0,
      labelWidth: 15,
      border: false,
      borderWidth: 1,
      borderColor: '#FFFFFF',
      linearType: 'custom'
    }
  },
  color: ['#1890FF', '#36CBCB', '#4ECB73', '#FBD437', '#F2637B', '#975FE5']
}

const userChartData = ref({
  categories: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
  series: [
    {
      name: '注册用户',
      data: [150, 230, 224, 218, 135, 147, 260],
      color: '#1890FF'
    },
    {
      name: '活跃用户',
      data: [90, 140, 160, 170, 120, 130, 190],
      color: '#4ECB73'
    }
  ]
})

const productChartData = ref({
  series: [
    {
      data: [
        { name: '电子产品', value: 1048 },
        { name: '服装', value: 735 },
        { name: '食品', value: 580 },
        { name: '家居', value: 484 },
        { name: '美妆', value: 300 }
      ]
    }
  ]
})

const recentActivities = ref([
  {
    type: 'user',
    icon: 'icon-user',
    title: '新用户注册',
    description: '张三注册成为新用户',
    time: '2小时前'
  },
  {
    type: 'product',
    icon: 'icon-product',
    title: '新商品上架',
    description: '管理员上架了5个新商品',
    time: '4小时前'
  },
  {
    type: 'order',
    icon: 'icon-order',
    title: '新订单',
    description: '李四购买了3个商品',
    time: '昨天'
  },
  {
    type: 'comment',
    icon: 'icon-comment',
    title: '新评论',
    description: '王五对商品进行了评价',
    time: '昨天'
  }
])

const fetchStats = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    
    // 获取统计数据
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getStats'
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.status === 1) {
      // 将统计数据赋值给stats变量
      stats.value = res.result.data || {
        users: {
          total: 0,
          activeUsers: 0,
          newUsers: 0
        },
        comments: {
          total: 0,
          totalLikes: 0,
          totalShares: 0,
          totalReplies: 0
        }
      }
    } else {
      uni.showToast({
        title: '获取统计数据失败',
        icon: 'none'
      })
    }
    
    // 更新图表数据
    updateChartData()
  } catch (error) {
    uni.hideLoading()
    console.error('获取统计数据失败:', error)
    uni.showToast({
      title: '获取统计数据失败',
      icon: 'none'
    })
  }
}

const updateChartData = async () => {
  try {
    uni.showLoading({
      title: '加载图表...'
    })
    
    // 获取用户增长趋势
    const userTrendRes = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getUserTrend',
          period: activePeriod.value
        })
      }
    })
    
    if (userTrendRes.result && userTrendRes.result.status === 1) {
      const trendData = userTrendRes.result.data
      if (trendData && trendData.dates && trendData.dates.length > 0) {
        userChartData.value = {
          categories: trendData.dates,
          series: [
            {
              name: '注册用户',
              data: trendData.registerCounts,
              color: '#1890FF'
            },
            {
              name: '活跃用户',
              data: trendData.activeCounts,
              color: '#4ECB73'
            }
          ]
        }
      }
    }
    
    // 获取商品分类分布数据
    // 注意：这里应该使用alldata云函数，因为原代码中的postManage函数不存在
    const productDistRes = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getProductList',
          category: true // 表示我们需要按分类统计
        })
      }
    })
    
    // 处理商品分类数据
    if (productDistRes.result && productDistRes.result.code === 0) {
      // 统计各分类商品数量
      const productData = productDistRes.result.data || []
      const categoryMap = {}
      
      productData.forEach(item => {
        const category = item.category || '未分类'
        if (!categoryMap[category]) {
          categoryMap[category] = 0
        }
        categoryMap[category]++
      })
      
      // 转换为图表所需格式
      const pieData = Object.keys(categoryMap).map(key => ({
        name: key,
        value: categoryMap[key]
      }))
      
      // 更新饼图数据
      if (pieData.length > 0) {
        productChartData.value = {
          series: [{
            data: pieData
          }]
        }
      }
    }
    
    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
    console.error('更新图表数据失败:', error)
    uni.showToast({
      title: '更新图表失败',
      icon: 'none'
    })
  }
}

const fetchRecentActivities = async () => {
  try {
    uni.showLoading({
      title: '加载活动...'
    })
    
    const res = await uniCloud.callFunction({
      name: 'alldata',
      data: {
        body: JSON.stringify({
          action: 'getRecentActivities',
          limit: 10
        })
      }
    })
    
    uni.hideLoading()
    
    if (res.result && res.result.status === 1) {
      recentActivities.value = res.result.data.map(activity => ({
        type: activity.type,
        icon: getActivityIcon(activity.type),
        title: activity.title,
        description: activity.description,
        time: formatActivityTime(activity.createTime)
      }))
    } else {
      console.error('获取最近活动失败:', res.result?.message || '未知错误')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('获取最近活动失败:', error)
    uni.showToast({
      title: '获取活动数据失败',
      icon: 'none'
    })
  }
}

const getActivityIcon = (type) => {
  const iconMap = {
    user: 'icon-user',
    product: 'icon-product',
    order: 'icon-order',
    comment: 'icon-comment'
  }
  return iconMap[type] || 'icon-default'
}

const formatActivityTime = (timestamp) => {
  const now = Date.now()
  const diff = now - timestamp
  
  if (diff < 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 1000)) + '分钟前'
  } else if (diff < 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (60 * 60 * 1000)) + '小时前'
  } else if (diff < 30 * 24 * 60 * 60 * 1000) {
    return Math.floor(diff / (24 * 60 * 60 * 1000)) + '天前'
  } else {
    const date = new Date(timestamp)
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
  }
}

// 监听时间周期变化
watch(activePeriod, () => {
  updateChartData()
})

onMounted(() => {
  fetchStats()
  fetchRecentActivities()
})
</script>

<style lang="scss" scoped>
.dashboard {
  .stat-cards {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10rpx 30rpx;
    
    .stat-card {
      flex: 1;
      min-width: 300rpx;
      background-color: #fff;
      margin: 10rpx;
      padding: 30rpx;
      border-radius: 15rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      display: flex;
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-5rpx);
        box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
      }
      
      .icon-box {
        width: 80rpx;
        height: 80rpx;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20rpx;
        
        .iconfont {
          font-size: 40rpx;
          color: #fff;
        }
        
        &.user-icon {
          background: linear-gradient(135deg, #1890FF, #36CBCB);
        }
        
        &.comment-icon {
          background: linear-gradient(135deg, #975FE5, #F2637B);
        }
        
        &.interaction-icon {
          background: linear-gradient(135deg, #FF8C00, #FF4D4F);
        }
      }
      
      .stat-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        
        .label {
          font-size: 26rpx;
          color: #666;
          margin-bottom: 10rpx;
        }
        
        .value {
          font-size: 48rpx;
          font-weight: bold;
          color: #333;
          margin-bottom: 10rpx;
        }
        
        .trend {
          font-size: 24rpx;
          color: #999;
          
          .up {
            color: #52c41a;
            margin: 0 4rpx;
          }
          
          .down {
            color: #ff4d4f;
            margin: 0 4rpx;
          }
        }
      }
    }
  }
  
  .chart-section {
    margin-bottom: 30rpx;
    
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .section-actions {
        .period-btn {
          display: inline-block;
          padding: 8rpx 20rpx;
          font-size: 24rpx;
          color: #666;
          margin-left: 10rpx;
          border-radius: 6rpx;
          cursor: pointer;
          
          &.active {
            background-color: #e6f7ff;
            color: #1890ff;
          }
        }
      }
    }
    
    .charts-container {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -10rpx;
      
      .chart-card {
        flex: 1;
        min-width: 500rpx;
        margin: 10rpx;
        background-color: #fff;
        border-radius: 15rpx;
        box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
        overflow: hidden;
        
        .chart-header {
          padding: 20rpx 30rpx;
          border-bottom: 1px solid #f0f0f0;
          
          .chart-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
          }
        }
        
        .chart-body {
          height: 500rpx;
          padding: 20rpx;
        }
      }
    }
  }
  
  .recent-activities {
    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      
      .section-title {
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
      }
      
      .view-all {
        font-size: 26rpx;
        color: #1890ff;
        cursor: pointer;
      }
    }
    
    .activities-list {
      background-color: #fff;
      border-radius: 15rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
      overflow: hidden;
      
      .activity-item {
        display: flex;
        align-items: center;
        padding: 30rpx;
        border-bottom: 1px solid #f0f0f0;
        
        &:last-child {
          border-bottom: none;
        }
        
        .activity-icon {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;
          
          .iconfont {
            font-size: 30rpx;
            color: #fff;
          }
          
          &.user {
            background-color: #1890ff;
          }
          
          &.product {
            background-color: #4ECB73;
          }
          
          &.order {
            background-color: #FF8C00;
          }
          
          &.comment {
            background-color: #975FE5;
          }
        }
        
        .activity-content {
          flex: 1;
          
          .activity-title {
            font-size: 28rpx;
            font-weight: bold;
            color: #333;
            margin-bottom: 8rpx;
          }
          
          .activity-desc {
            font-size: 24rpx;
            color: #666;
          }
        }
        
        .activity-time {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .dashboard {
    .stat-cards {
      flex-direction: column;
      
      .stat-card {
        min-width: auto;
      }
    }
    
    .charts-container {
      flex-direction: column;
      
      .chart-card {
        min-width: auto;
      }
    }
  }
}
</style> 